//app.js
import { getCode, canIUse, showModal, getUpdateManager } from './common/env';
import { getUserOpenId, setUserId, setUserOpenId, setUserToken, setUserInfo } from './biztools/wex';
import { dealLandingPage } from './biztools/common';
import { isFunction } from './common/utils';
import { userIdentify } from './api/usr';
import event from "./common/event";
// mixin
import './common/mixins';

App({
    async onLaunch(options) {
        console.log('onLaunch => 参数:', options)
        // 更新管理
        if (canIUse('getUpdateManager')) {
            const updateManager = getUpdateManager()
            updateManager.onCheckForUpdate((res) => {
                console.log('onCheckForUpdate => 结果', res);
                if (res.hasUpdate) {
                    console.log('onCheckForUpdate hasUpdate 有更新');
                    updateManager.onUpdateReady(async () => {
                        const res = await showModal({
                            title: '更新提示',
                            content: '新版本已经准备好，是否重启应用？',
                        });
                        if (res.confirm) {
                            updateManager.applyUpdate();
                        }
                    })
                    updateManager.onUpdateFailed(async () => {
                        await showModal({
                            title: '已经有新版本了哟~',
                            content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
                        });
                    });
                }
            })
        }
    },
    async onShow(options) {
        console.log('onShow => 参数:', options)
        const { path, query } = options;
        const openId = getUserOpenId();
        let uiParams = dealLandingPage(path, query);
        uiParams.code = await getCode();
        openId && (uiParams.openId = openId);
        console.log('userIdentify => 参数', uiParams)
        const user = await userIdentify(uiParams);
        setUserId(user.userId);
        setUserOpenId(user.openId);
        setUserToken(user.apiToken);
        setUserInfo(user);
        this.globalData.isReadyAuth = user.apiToken ? true : false;
        if (!this.globalData.isLaunch && this.userIdentifyCallback && isFunction(this.userIdentifyCallback)) {
            console.log('userIdentifyCallback => 参数：', query)
            this.userIdentifyCallback(query);
        }
        this.globalData.isLaunch = true;
    },
    globalData: {
        isReadyAuth: false,
        isLaunch: false,
    },
    event: new event(),
})